import BackPage from '@/components/BackPage';
import SelectOne from '@/components/SelectOne';
import { getAdsList } from '@/services/ads';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button } from 'antd';
import { useCallback, useEffect, useRef, useState } from 'react';
import ConfirmModal from './components/ConfirmModal';
import styles from './index.less';

const PostAds: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const colorThem = localStorage.getItem('color') || '#1a7721';
  const [selectList, setSelectList] = useState<any[]>([]);
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [current, setCurrent] = useState<any>({});
  const [confirmModal, setConfirmModal] = useState<boolean>(false);

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const getList = useCallback(async () => {
    try {
      const res = await getAdsList({ pageIndex: currentPage, pageSize: 13 });
      setTotal(res.total);
      setList(res.list);
    } catch (error) {
      console.error(error);
    }
  }, [currentPage]);

  useEffect(() => {
    getList();
  }, [getList]);

  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '卖家编号',
      dataIndex: 'id',
      copyable: true,
      ellipsis: true,
      // tip: '标题过长会自动收缩',
    },
    {
      title: '投放位置',
      ellipsis: true,
      render: (_, record) => [
        <div key={record.id}>{record.wherePost === '1' ? '首页轮播图推送' : '首页推荐推送'}</div>,
      ],
    },
    {
      disable: true,
      title: '状态',
      dataIndex: 'ifApproval',
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueType: 'select',
      valueEnum: {
        all: { text: '超长'.repeat(50) },
        '0': {
          text: '待审批',
          status: 'Error',
        },
        '1': {
          text: '已通过',
          status: 'Success',
          disabled: true,
        },
        '2': {
          text: '已退回',
          status: 'Success',
          disabled: true,
        },
      },
    },
    {
      title: '付款金额',
      ellipsis: true,
      render: (_, record) => [<div key={record.id}>{`${record.money}元`}</div>],
    },
    // {
    //   title: '起止时间',
    //   key: 'date',
    //   dataIndex: 'date',
    //   valueType: 'date',
    //   render: (text, record) => [
    //     <div key={record.id}>
    //       {`${moment(Number(record.timeStart)).format('YYYY-MM-DD HH:mm:ss')}`}
    //       <br />
    //       {`-`}
    //       <br />
    //       {`${moment(Number(record.timeEnd)).format('YYYY-MM-DD HH:mm:ss')}`}
    //     </div>,
    //   ],
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      render: (text, record) => [
        <div key={record.id} className={styles.action}>
          {record.ifApproval === '2' ? (
            <div>该审批已退回</div>
          ) : record.ifApproval === '1' ? (
            <div>该审批已通过</div>
          ) : (
            <Button
              key={record.id}
              className={styles.actionBtn}
              onClick={() => {
                setConfirmModal(true);
                setCurrent({
                  ...current,
                  id: record.id,
                  payId: record.payId,
                  money: record.money,
                  wherePost: record.wherePost,
                  goodsId: record.goodsId,
                });
              }}
              style={{ border: `1px solid ${colorThem}`, color: colorThem }}
            >
              审批
            </Button>
          )}
        </div>,
      ],
    },
  ];

  return (
    <BackPage thisRoute={'/ads'} lastRoute={'广告投放'}>
      <div className={styles.container}>
        <SelectOne
          searchText={'卖家编号'}
          fromWhere={'ads'}
          selected={(value) => {
            setSelectList(value);
          }}
          clear={() => {
            setSelectList([]);
          }}
        />
        <ProTable<any>
          columns={columns}
          actionRef={actionRef}
          cardBordered={false}
          dataSource={selectList.length !== 0 ? selectList : list}
          editable={{
            type: 'multiple',
          }}
          columnsState={{
            persistenceKey: 'pro-table-singe-demos',
            persistenceType: 'localStorage',
            onChange(value) {
              console.log('value: ', value);
            },
          }}
          rowKey="id"
          search={false}
          options={false}
          pagination={{
            total,
            current: currentPage, // 当前页数
            pageSize: 13, // 每页条数
            size: 'small', // 分页的样式
            hideOnSinglePage: true, // 只有一页时是否隐藏分页器
            onChange: handlePageChange, // 分页的方法
          }}
          dateFormatter="string"
          headerTitle=""
        />
        {confirmModal && (
          <ConfirmModal
            handleCancel={() => {
              setConfirmModal(false);
            }}
            current={current}
            getList={getList}
          />
        )}
      </div>
    </BackPage>
  );
};
export default PostAds;
